package controllers

import (
	"cronjob/jobs"
	"cronjob/libs"
	"cronjob/models"
	"time"

	"github.com/astaxie/beego"
)

type IndexController struct {
	BaseController
}

func (this *IndexController) Index() {

	this.TplName = this.controllerName + "/main.html"
}

func (this *IndexController) Start() {
	//-----------最近执行的任务，最近执行成功的任务数量，最近执行失败的任务数量------------

	//查询执行20条数据
	logs, _ := models.TaskLogGetList(1, 20)

	recentLogs := make([]map[string]interface{}, len(logs))
	faillog := 0
	oklog := 0
	for k, tkLog := range logs {

		// row字段显示的字段 task_name  start_time   id  status

		row1 := make(map[string]interface{})
		//根据执行的taskid获取任务名称
		task, err := models.TaskGetById(tkLog.TaskId)

		if err != nil {
			row1["task_name"] = ""
			recentLogs[k] = row1
			continue
		}

		row1["task_name"] = task.TaskName

		row1["start_time"] = beego.Date(time.Unix(tkLog.CreateTime, 0), "Y-m-d H:i:s")
		row1["id"] = task.Id
		row1["status"] = tkLog.Status

		recentLogs[k] = row1

		if tkLog.Status == 0 {
			oklog++
		} else {
			faillog++
		}
	}

	this.Data["recentLogs"] = recentLogs
	this.Data["faillog"] = faillog
	this.Data["oklog"] = oklog

	//服务器的配置信息
	//info := libs.SystemInfo(StartTime)
	sysinfo := libs.SystemInfo(models.StartTime)

	this.Data["sysInfo"] = sysinfo

	//----------即将执行的任务, 即将执行的任务的数量---------------
	//服务器分组信息
	//[服务器分组id]服务器分组名称
	groups_map := serverGroupLists(this.serverGroups, this.userID)

	//获取最近执行的20条命令
	entries := jobs.GetEntries(20)

	//task_name   task_group   task_id  next_time
	//创建切片，用于存储即将执行的任务
	jobList := make([]map[string]interface{}, len(entries))

	//遍历即将执行的任务的切片
	for k, v := range entries {
		row := make(map[string]interface{})
		job := v.Job.(*jobs.Job)
		//根据任务id获取任务TaskGetById
		task, _ := models.TaskGetById(job.GetId())
		row["task_id"] = task.Id
		row["task_name"] = task.TaskName
		row["task_group"] = groups_map[task.GroupId]
		row["next_time"] = beego.Date(v.Next, "Y-m-d H:i:s")
		jobList[k] = row
	}

	//即将执行的任务的长度
	startJob := len(jobList)
	this.Data["startJob"] = startJob
	this.Data["jobs"] = jobList

	total := models.TaskGetCount()
	this.Data["totalJob"] = total

	this.display()
	//this.Layout = "public/layout.html"
	//this.TplName = this.controllerName + "/start.html"
}
